namespace RBAC.Read.Api.Application.Handler.DataBashboard
{
    using MediatR;
    using Microsoft.Extensions.Logging;
    using RBAC.Domain.DataDashboard;
    using RBAC.ErrorCode;
    using RBAC.Interstructrue.Base;
    using RBAC.Read.Api.Application.Command.DataBashboard;
    using RBAC.Read.Api.Application.Dto.DataBashboard;

    /// <summary>
    /// 看板任务 分页查询 处理器
    /// </summary>
    public class GetKanbanTasksPageHandler : IRequestHandler<GetKanbanTasksPageCommand, APIPaging<KanbanTasksListDto>>
    {
        private readonly IBaseRepository<KanbanTasks> repository;
        private readonly ILogger<GetKanbanTasksPageHandler> logger;

        public GetKanbanTasksPageHandler(
            IBaseRepository<KanbanTasks> repository,
            ILogger<GetKanbanTasksPageHandler> logger)
        {
            this.repository = repository;
            this.logger = logger;
        }

        public Task<APIPaging<KanbanTasksListDto>> Handle(GetKanbanTasksPageCommand request, CancellationToken cancellationToken)
        {
            var result = new APIPaging<KanbanTasksListDto>();
            try
            {
                logger.LogInformation("开始获取看板任务分页 PageIndex={PageIndex}, PageSize={PageSize}", request.PageIndex, request.PageSize);

                var where = BuildWhereClause(request);
                var parameters = BuildParameters(request);

                var (data, total) = repository.GetPaged(request.PageIndex, request.PageSize, where, request.OrderBy, parameters);

                var list = data.Select(o => new KanbanTasksListDto
                {
                    Id = o.Id,
                    WorkOrderNo = o.WorkOrderNo,
                    Status = o.Status,
                    ProductNo = o.ProductNo,
                    ProductName = o.ProductName,
                    ProductSpec = o.ProductSpec,
                    ProcessRoute = o.ProcessRoute,
                    OperationNo = o.OperationNo,
                    OperationName = o.OperationName,
                    PlannedQty = o.PlannedQty,
                    QualifiedQty = o.QualifiedQty,
                    UnqualifiedQty = o.UnqualifiedQty,
                    CreateTime = o.CreateTime,
                    CreateUser = o.CreateUser
                }).ToList();

                result.Code = APIEnums.Success;
                result.PageDatas = list;
                result.TotalCount = total;
                result.Msg = "获取看板任务分页成功";
            }
            catch (Exception ex)
            {
                logger.LogError(ex, "获取看板任务分页失败: {Message}", ex.Message);
                result.Code = APIEnums.Error;
                result.Msg = "获取看板任务分页失败";
                result.PageDatas = new List<KanbanTasksListDto>();
                result.TotalCount = 0;
            }

            return Task.FromResult(result);
        }

        /// <summary>
        /// 构建 WHERE 条件子句
        /// </summary>
        private string BuildWhereClause(GetKanbanTasksPageCommand request)
        {
            var conditions = new List<string>();

            if (!string.IsNullOrWhiteSpace(request.WorkOrderNo))
            {
                conditions.Add("WorkOrderNo LIKE @WorkOrderNo");
            }
            if (!string.IsNullOrWhiteSpace(request.Status))
            {
                conditions.Add("Status = @Status");
            }
            if (!string.IsNullOrWhiteSpace(request.ProductNo))
            {
                conditions.Add("ProductNo LIKE @ProductNo");
            }
            if (!string.IsNullOrWhiteSpace(request.ProductName))
            {
                conditions.Add("ProductName LIKE @ProductName");
            }
            if (!string.IsNullOrWhiteSpace(request.OperationName))
            {
                conditions.Add("OperationName LIKE @OperationName");
            }
            if (request.StartDate.HasValue)
            {
                conditions.Add("CreateTime >= @StartDate");
            }
            if (request.EndDate.HasValue)
            {
                conditions.Add("CreateTime <= @EndDate");
            }

            // 添加逻辑删除过滤
            conditions.Add("IsDeleted = 0");

            return conditions.Count > 0 ? string.Join(" AND ", conditions) : "IsDeleted = 0";
        }

        /// <summary>
        /// 构建查询参数
        /// </summary>
        private object BuildParameters(GetKanbanTasksPageCommand request)
        {
            var p = new Dictionary<string, object>();

            if (!string.IsNullOrWhiteSpace(request.WorkOrderNo))
            {
                p["WorkOrderNo"] = $"%{request.WorkOrderNo.Trim()}%";
            }
            if (!string.IsNullOrWhiteSpace(request.Status))
            {
                p["Status"] = request.Status.Trim();
            }
            if (!string.IsNullOrWhiteSpace(request.ProductNo))
            {
                p["ProductNo"] = $"%{request.ProductNo.Trim()}%";
            }
            if (!string.IsNullOrWhiteSpace(request.ProductName))
            {
                p["ProductName"] = $"%{request.ProductName.Trim()}%";
            }
            if (!string.IsNullOrWhiteSpace(request.OperationName))
            {
                p["OperationName"] = $"%{request.OperationName.Trim()}%";
            }
            if (request.StartDate.HasValue)
            {
                p["StartDate"] = request.StartDate.Value.Date;
            }
            if (request.EndDate.HasValue)
            {
                var end = request.EndDate.Value;
                if (end.TimeOfDay == TimeSpan.Zero)
                {
                    end = end.Date.AddDays(1).AddTicks(-1);
                }
                p["EndDate"] = end;
            }

            return p;
        }
    }
}
